package cn.texous.dns.controller;

import cn.texous.dns.configure.OtherProperties;
import cn.texous.dns.service.api.MailSendService;
import cn.texous.dns.util.CheckUtils;
import cn.texous.dns.util.FileUtils;
import cn.texous.dns.util.IpUtils;
import cn.texous.dns.util.ReplaceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/5/27 18:25
 */
@Slf4j
@RestController
@RequestMapping("/mail")
public class SendMailController {

    @Autowired
    private OtherProperties otherProperties;
    @Autowired
    private MailSendService mailSendService;

    /***/
    @GetMapping("/send")
    public Map<String, String> sendSms(HttpServletRequest request) {
        Map<String, String> result = new HashMap<>();
        String code = request.getParameter("code");
        String email = request.getParameter("email");
        // 邮件类型：1=普通文本，2=html
        String sendType = request.getParameter("mailType");
        // 业务类型：1=注册验证码，2=修改密码验证码
        String businessType = request.getParameter("businessType");
        String errorMsg = null;
        // 发送结果代码：0=失败，1=成功
        String resultCode = "0";
        log.info("发送邮箱验证码：code={}, email={}, sendType={}, businessType={}",
                code, email, sendType, businessType);
        try {
            String ip = IpUtils.getIpAddress(request);
            if (otherProperties.getIp().getWhitelist().contains(ip)) {
                Integer type = sendType == null ? 1 : Integer.parseInt(sendType);
                Integer bt = businessType == null ? 1 : Integer.parseInt(businessType);
                if (CheckUtils.isEmail(email)) {
                    String[] mails = new String[]{email};
                    switch (type) {
                        case 1:
                            mailSendService.sendSimpleMail(
                                    mails, otherProperties.getMail().getSubject(bt),
                                    getContent(bt, code));
                            resultCode = "1";
                            break;
                        case 2:
                            mailSendService.sendHtmlMail(
                                    mails, otherProperties.getMail().getSubject(bt),
                                    getHtml(bt, code));
                            resultCode = "1";
                            break;
                        default:
                            throw new RuntimeException("不支持的邮件类型");
                    }
                    log.info("邮件发送成功！");
                } else {
                    errorMsg = "邮箱格式不正确";
                    log.error("邮箱格式不正确：{}", email);
                }
            }
        } catch (Exception e) {
            log.error(String.format("验证码发送失败：%s", email), e);
            errorMsg = "验证码发送失败";
        }

        result.put("result", resultCode);
        result.put("errorMsg", errorMsg);
        return result;
    }

    private String getContent(Integer bt, String code) {
        String content = otherProperties.getMail().getContent(bt);
        return insertCode(content, code);
    }

    private String getHtml(Integer bt, String code) {
        String filePath = otherProperties.getMail().getHtml(bt);
        String content = FileUtils.getFromClassPath2String(filePath);
        return insertCode(content, code);
    }

    private String insertCode(String content, String code) {
        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        ReplaceUtils.ReplaceParam param = ReplaceUtils.ReplaceParam.builder()
                .resource(content)
                .params(params)
                .identifierStart(ReplaceUtils.HASHTAG_PARENTHESIS_START)
                .identifierEnd(ReplaceUtils.PARENTHESIS_END)
                .build();
        return ReplaceUtils.replace(param);
    }

}
